import React from 'react';
import { messages, deepFullCopy } from 'share/common';
import errorMessage from 'share/errorMessage';
import {
  Table, Input, Select, Popconfirm, Button, Icon, message, Modal
} from 'antd';

const { Option } = Select;
import Chooser from 'components/chooser';

import consumerService from '../consumer.service';
import 'styles/supplier-management/new-consumer-management/cmbc-open-detail.scss';
import { connect } from 'react-redux';

@connect(mapStateToProps)
class CMBCOpenDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      saveLoading: false,
      billMonthArray: [
        {label: messages('common.this.month')/* 当月 */, value: 'CURRENT_MONTH'},
        {label: messages('supplier.key643')/* 上月 */, value: 'LAST_MONTH'},
        {label: `${messages('common.this.month')/* 当月 */}, ${messages('supplier.key643')}`/* 上月 */, value: 'CURRENT_MONTH,LAST_MONTH'}
      ],
      columns: [{
        title: messages('supplier.key1'/* 账户信息(必填) */),
        children: [{
          title: messages('supplier.key644')/* 公司 */,
          dataIndex: 'company',
          render: (value, record, index) => (
            <Chooser
              type="available_company"
              valueKey="companyOID"
              labelKey="name"
              value={this.state.selectedCompany[index] ? [this.state.selectedCompany[index]] : undefined}
              single
              placeholder={messages('common.please.select')}
              onChange={(item) => this.handleChange(item[0] || {}, record.indexTag, 'companyOID')}
            />
          )
        }, {
          title: messages('supplier.key2'/* 客户号 */),
          dataIndex: 'clientId',
          render: (value, record) => (
            <Input
              type="number"
              placeholder={messages('common.please.enter')}
              value={value}
              onChange={(e) => this.handleChange(e.target.value, record.indexTag, 'clientId')}
            />
          )
        }, {
          title: messages('supplier.key3'/* 密码 */),
          dataIndex: 'clientSecret',
          render: (value, record) => (
            <Input
              type="password"
              autoComplete="new-password"
              placeholder={messages('common.please.enter')}
              maxLength="8"
              value={value}
              onChange={(e) => this.handleChange(e.target.value, record.indexTag, 'clientSecret')}
            />
          )
        }, {
          title: messages('supplier.key4'/* 成本中心号 */),
          dataIndex: 'corNum',
          render: (value, record) => (
            <Input
              type="number"
              placeholder={messages('common.please.enter')}
              value={value}
              onChange={(e) => this.handleChange(e.target.value, record.indexTag, 'corNum')}
            />
          )
        }]
      }, {
        title: messages('supplier.key5'/* 逾期设置(非必填) */),
        children: [{
          title: messages('supplier.key6'/* 报销期限 */),
          dataIndex: 'deadLineDate',
          render: (value, record) => {
            const deadLineDateArray = [];
            for (let i = 1; i < 32; i++) {
              deadLineDateArray.push({label: messages('supplier.key645', {arg1: i})/* 每月{arg1}日 */, value: `${i}`});
            }
            return (
              <Select
                showSearch
                style={{width: '100%'}}
                value={value || []}
                placeholder={messages('common.please.select')}
                optionFilterProp="children"
                onChange={(e) => this.handleChange(e, record.indexTag, 'deadLineDate')}
              >
                {deadLineDateArray.map((item) => (
                  <Option key={item.value} value={item.value}>{item.label}</Option>
                ))}
              </Select>
            );
          }
        }, {
          title: messages('supplier.key7'/* 账单月 */),
          dataIndex: 'billMonth',
          render: (value, record) => (
            <Select
              style={{width: '100%'}}
              value={record.billMonth ? record.billMonth : []}
              placeholder={messages('common.please.select')}
              onChange={(e) => this.handleChange(e, record.indexTag, 'billMonth')}
            >
              {this.state.billMonthArray.map((item) => (
                <Option key={item.value} value={item.value}>{item.label}</Option>
              ))}
            </Select>
          )
        }]
      },
      {
        title: messages('supplier.key823')/* 付款账户（非必填） */,
        dataIndex: 'paymentBankNum',
        render: (value, record, index) => (
          <Chooser
            type="bankAccountNumber"
            labelKey="bankAccountName"
            valueKey="bankAccountNumber"
            onChange={(item) => this.handleChange(item[0] || {}, record.indexTag, 'paymentBankNum')}
            value={this.state.selectedPaymentBankNum[index] ? [this.state.selectedPaymentBankNum[index]] : undefined}
            single
            disabled={!this.state.selectedCompany[index]}
            selectorItem={{
              title: messages('financial-management.key147'/* 公司银行账号 */),
              url: `/api/CompanyBank/getAuthCompanyBank/${props.user.userOID}`,
              searchForm: [],
              columns: [
                { title: messages('financial-management.key148'/* 账号名称 */), dataIndex: 'bankAccountName' },
                { title: messages('financial-management.key149'/* 付款账号 */), dataIndex: 'bankAccountNumber' },
                { title: messages('financial-management.key150'/* 银行名称 */), dataIndex: 'bankName' }
              ],
              key: 'companyBank.bankAccountNumber'
            }}
            listExtraParams={{
              companyId: this.state.selectedCompany[index] ? this.state.selectedCompany[index].companyId : void 0,
              setOfBooksId: this.state.selectedCompany[index] ? this.state.selectedCompany[index].setOfBooksId : void 0
            }}
            placeholder={messages('common.please.select')}
            locale={{ emptyText: this.renderEmptyText() }}
            />
        )
      },
      {
        title: messages('common.operation')/* 操作 */,
        dataIndex: 'operate',
        width: 100,
        render: (value, record) => (
          <Popconfirm
            title={messages('common.confirm.delete')/* 确定要删除吗？ */}
            overlayStyle={{minWidth: 160}}
            onConfirm={() => this.handleDelete(record)}
          >
            <a>{messages('common.delete')}</a>
          </Popconfirm>
        )
      }],
      dataSource: [],
      selectedCompany: [],
      selectedPaymentBankNum: []
    };
  }

  componentDidMount() {
    this.getList();
  }

  renderEmptyText = () => (
    <span>
      {messages('supplier.key861')/* 该公司无招商银行付款账户，请至 */}
      {' '}
&nbsp;
      <span className="jump-color" onClick={this.handleJump}>{messages('supplier.key862')/* 财务管理-支付设置-公司账户 */}</span>
      {messages('supplier.key863')/* 界面添加银行账户 */}
    </span>
  );

  handleJump = () => {
    window.open('/main/pay-setting/company-account-setting');
  };

  getList = () => {
    this.setState({ loading: true });
    consumerService.getCMBCAccount().then((res) => {
      const rows = deepFullCopy(res.data.rows || {});
      const dataSource = deepFullCopy(rows.tenantBankCardCfgList || []);
      const selectedCompany = []; const selectedPaymentBankNum = [];
      dataSource.map((item, index) => {
        item.indexTag = index;
        selectedCompany[index] = {
          companyOID: item.companyOID,
          name: item.companyName,
          companyId: item.companyId,
          setOfBooksId: item.setOfBooksId
        };
        item.paymentBankNum && (selectedPaymentBankNum[index] = {
          key: item.paymentBankNum,
          bankAccountNumber: item.paymentBankNum,
          bankAccountName: item.paymentBankName

        });
      });
      this.setState({
        loading: false, dataSource, selectedCompany, selectedPaymentBankNum
      });
    });
  };

  // 新增账户信息添加表格行
  addRow = () => {
    const { dataSource } = this.state;
    const newData = {
      indexTag: dataSource.length,
      clientId: '',
      clientSecret: '',
      corNum: '',
      deadLineDate: '',
      billMonth: ''
    };
    this.setState({ dataSource: [...dataSource, newData] });
  };

  handleChange = (value, indexTag, column) => {
    const { selectedCompany, selectedPaymentBankNum } = this.state;
    const newData = [...this.state.dataSource];
    const target = newData.filter((item) => indexTag === item.indexTag)[0];
    if (target) {
      if (column === 'companyOID') {
        value.companyOID
          ? selectedCompany[indexTag] = {
            companyOID: value.companyOID,
            name: value.name,
            companyId: value.id,
            setOfBooksId: value.setOfBooksId
          }
          : selectedCompany[indexTag] = void 0;
        value.companyOID !== target.companyOID && (selectedPaymentBankNum[indexTag] = void 0);
        target[column] = value.companyOID;
      } else if (column === 'paymentBankNum') {
        target[column] = value.bankAccountNumber;
        value.bankAccountNumber
          ? selectedPaymentBankNum[indexTag] = {
            bankAccountNumber: value.bankAccountNumber,
            bankAccountName: value.bankAccountName,
            key: value.bankAccountNumber
          }
          : selectedPaymentBankNum[indexTag] = void 0;
      } else {
        target[column] = value;
      }
      this.setState({ dataSource: newData, selectedCompany, selectedPaymentBankNum });
    }
  };

  // 删除行
  handleDelete = (record) => {
    const { dataSource, selectedCompany, selectedPaymentBankNum } = this.state;
    const data = deepFullCopy(dataSource); const
      company = deepFullCopy(selectedCompany);
    const deleteIndex = dataSource.findIndex((item) => item.indexTag === record.indexTag);
    data.splice(deleteIndex, 1);
    company.splice(deleteIndex, 1);
    selectedPaymentBankNum.splice(deleteIndex, 1);
    data.map((item, index) => item.indexTag = index);
    this.setState({ dataSource: data, selectedCompany: company, selectedPaymentBankNum});
  };

  handleSave = () => {
    const { openStatus } = this.props;
    const { dataSource } = this.state;
    if (openStatus && dataSource.length === 0) {
      Modal.confirm({
        title: messages('supplier.key98'/* 无有效账户信息，将自动关闭该服务 */),
        content: messages('supplier.key99'/* 关闭后不能在汇联易中使用招行商务卡服务 */),
        okText: messages('supplier.key100'/* 继续关闭 */),
        onOk: this.handleUpdate
      });
      return;
    }
    if (dataSource.length === 0) {
      message.error(messages('supplier.key646')/* 客户不能为空 */);
      return;
    }
    const verifyCompany = dataSource.some((item) => !item.companyOID);
    if (verifyCompany) {
      message.error(messages('supplier.key647')/* 公司不能为空 */);
      return;
    }
    const verifyId = dataSource.some((item) => // 验证客户号
      item.clientId.length !== 8);
    if (verifyId) {
      message.error(messages('supplier.key648')/* 客户号为8位 */);
      return;
    }
    const verifySecret = dataSource.some((item) => // 验证密码
      item.clientSecret.length !== 8);
    if (verifySecret) {
      message.error(messages('supplier.key649')/* 密码为8位 */);
      return;
    }
    const verifyCorNum = dataSource.some((item) => // 验证成本中心号
      item.corNum.length !== 10);
    if (verifyCorNum) {
      message.error(messages('supplier.key650')/* 成本中心号为10位 */);
      return;
    }
    openStatus ? this.handleUpdate() : this.handleOpen();
  };

  // 开通商务卡
  handleOpen = () => {
    this.setState({ saveLoading: true });
    consumerService.updateBankcardStatus('CMBC', 1).then((res) => {
      if (res.data.success) {
        this.handleUpdate();
      } else {
        message.error(res.data.message || messages('common.save.filed'/* 保存失败 */));
      }
    }).catch((e) => {
      this.setState({ saveLoading: false });
      errorMessage(e.response, messages('common.save.filed'/* 保存失败 */));
    });
  };

  // 更新商务卡账号列表
  handleUpdate = () => {
    const params = {
      status: 1,
      tenantBankCardCfgList: this.state.dataSource
    };
    this.setState({ loading: true, saveLoading: true });
    consumerService.updateCMBCService(params).then((res) => {
      this.setState({ saveLoading: false });
      if (res.data.success) {
        message.success(messages('common.save.success', {name: ''})/* 保存成功 */);
        this.props.onOpen();
        this.getList();
      } else {
        this.setState({ loading: false });
        message.error(res.data.message || messages('common.save.filed'/* 保存失败 */));
      }
    }).catch((e) => {
      this.setState({ loading: false, saveLoading: false });
      errorMessage(e.response, messages('common.save.filed'/* 保存失败 */));
    });
  };

  render() {
    const {
      loading, saveLoading, columns, dataSource
    } = this.state;
    return (
      <div className="cmbc-open-detail">
        <div className="notice-header">{messages('supplier.key167'/* 设置账号及逾期规则 */)}</div>
        <div className="notice-content">{messages('supplier.key168'/* 设置后系统将在报销期限日凌晨检查未审核通过的费用或商务卡消费，并标记为已逾期 */)}</div>
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          pagination={false}
          bordered
          size="middle"
        />
        <Button type="dashed" className="button-add-row" onClick={this.addRow}>
          <Icon type="plus" />
          {' '}
          {messages('supplier.key63'/* 新增账户信息 */)}
        </Button>
        <Button type="primary" className="button-save" loading={saveLoading} onClick={this.handleSave}>
          {messages('common.save')}
        </Button>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user
  };
}

export default CMBCOpenDetail;
